<template>
    <div class='container'>
        <!-- 页面头部 -->
        <page-header title="参赛作品" @heightChange="handleHeaderHeightChange" />

        <!-- 搜索栏 -->
        <view class="search-section">
            <view class="search-box">
                <uni-icons type="search" size="20" color="#666"></uni-icons>
                <input class="search-input" placeholder="搜索作品名称或作者" v-model="searchKeyword"
                    @input="handleSearchInput" />
                <view class="search-btn" @click="handleSearchButtonClick">
                    <view>搜索</view>
                </view>
            </view>
        </view>

        <!-- 筛选标签 -->
        <view class="filter-section">
            <scroll-view class="filter-scroll" scroll-x="true">
                <view class="filter-tags">
                    <view class="filter-tag" :class="{ active: currentFilter === 'all' }"
                        @click="handleFilterTagClick('all')">
                        <view>全部</view>
                    </view>
                    <view class="filter-tag" :class="{ active: currentFilter === 'latest' }"
                        @click="handleFilterTagClick('latest')">
                        <view>最新</view>
                    </view>
                    <view class="filter-tag" :class="{ active: currentFilter === 'popular' }"
                        @click="handleFilterTagClick('popular')">
                        <view>热门</view>
                    </view>
                    <view class="filter-tag" :class="{ active: currentFilter === 'voted' }"
                        @click="handleFilterTagClick('voted')">
                        <view>已投票</view>
                    </view>
                </view>
            </scroll-view>
        </view>

        <!-- 作品列表 -->
        <view class="works-section">
            <view class="works-header">
                <view class="works-count">
                    <view>共 {{ totalCount }} 个作品</view>
                </view>
                <view class="sort-btn" @click="handleSortButtonClick">
                    <uni-icons type="sort" size="16" color="#666"></uni-icons>
                    <view>排序</view>
                </view>
            </view>

            <view class="works-list">
                <view class="work-item" v-for="(work, index) in worksList" :key="work.id"
                    @click="handleWorkItemClick(work)">
                    <view class="work-image-container">
                        <image class="work-image" :src="work.image" mode="aspectFill" />
                        <view class="work-rank" v-if="work.rank">
                            <view class="rank-text">第{{ work.rank }}名</view>
                        </view>
                    </view>
                    <view class="work-info">
                        <view class="work-title">{{ work.title }}</view>
                        <view class="work-author">作者：{{ work.author }}</view>
                        <view class="work-desc">{{ work.description }}</view>
                        <view class="work-stats">
                            <view class="stat-item">
                                <uni-icons type="heart" size="16" color="#ff4757"></uni-icons>
                                <view class="stat-text">{{ work.votes }}票</view>
                            </view>
                            <view class="stat-item">
                                <uni-icons type="eye" size="16" color="#666"></uni-icons>
                                <view class="stat-text">{{ work.views }}浏览</view>
                            </view>
                            <view class="stat-item">
                                <uni-icons type="chat" size="16" color="#666"></uni-icons>
                                <view class="stat-text">{{ work.comments }}评论</view>
                            </view>
                        </view>
                        <view class="work-meta">
                            <view class="meta-item">
                                <uni-icons type="calendar" size="14" color="#666"></uni-icons>
                                <view class="meta-text">{{ work.createTime }}</view>
                            </view>
                            <view class="meta-item">
                                <uni-icons type="location" size="14" color="#666"></uni-icons>
                                <view class="meta-text">{{ work.category }}</view>
                            </view>
                        </view>
                    </view>
                    <view class="work-actions">
                        <button class="vote-btn" :class="{ 'voted': work.hasVoted }"
                            @click.stop="handleVoteButtonClick(work)">
                            <view>{{ work.hasVoted ? '已投票' : '投票' }}</view>
                        </button>
                    </view>
                </view>
            </view>

            <!-- 加载更多 -->
            <view class="load-more" v-if="hasMore">
                <view class="load-more-btn" @click="handleLoadMoreButtonClick">
                    <view>{{ isLoading ? '加载中...' : '加载更多' }}</view>
                </view>
            </view>

            <!-- 无数据提示 -->
            <view class="empty-state" v-if="worksList.length === 0 && !isLoading">
                <uni-icons type="info" size="60" color="#ccc"></uni-icons>
                <view class="empty-text">暂无参赛作品</view>
                <view class="empty-desc">快来提交您的作品吧</view>
            </view>
        </view>

        <!-- 底部导航栏 -->
        <page-bottom pageUrl="/pages-vote/Index" @navClick="handleTabClick" @heightChange="handleBottomHeightChange" />
    </div>
</template>

<script>
// 结构
import {
    defineComponent,
    onMounted,
    ref,
    reactive,
    computed
} from 'vue';
// 模块化
import PageHeader from '@/components/PageHeader.vue';
import PageBottom from '@/components/PageBottom.vue';

export default defineComponent({
    name: 'EntryList', // 组件名称
    props: {
        // 接收父组件数据

    },
    components: {
        PageHeader,
        PageBottom
    },
    // 主要是组件内交互事件
    setup(props, ctx) {
        // 这里没有this,直接使用props里数据
        // 进行数据的定义和初始化。object style interactive
        onMounted(() => { });

        // ===== 响应式对象 =====
        // 头部高度相关数据
        const headerHeight = ref(0);
        const bottomHeight = ref(0);

        // 搜索关键词
        const searchKeyword = ref('');

        // 当前筛选条件
        const currentFilter = ref('all');

        // 作品列表数据
        const worksList = ref([
            {
                id: 1,
                title: '创新项目A',
                author: '张三',
                description: '这是一个具有创新性的项目，展现了团队协作和创新能力，在技术领域取得了重要突破',
                image: '/static/images/work1.jpg',
                votes: 156,
                views: 234,
                comments: 23,
                rank: 1,
                hasVoted: false,
                createTime: '2024-03-15',
                category: '技术创新'
            },
            {
                id: 2,
                title: '技术突破B',
                author: '李四',
                description: '在技术领域取得了重要突破，为公司发展做出贡献，提升了整体技术水平',
                image: '/static/images/work2.jpg',
                votes: 142,
                views: 198,
                comments: 18,
                rank: 2,
                hasVoted: true,
                createTime: '2024-03-14',
                category: '产品设计'
            },
            {
                id: 3,
                title: '服务优化C',
                author: '王五',
                description: '优化了客户服务流程，提升了客户满意度，改善了用户体验',
                image: '/static/images/work3.jpg',
                votes: 128,
                views: 176,
                comments: 15,
                rank: 3,
                hasVoted: false,
                createTime: '2024-03-13',
                category: '服务改进'
            }
        ]);

        // 列表相关数据
        const totalCount = ref(156);
        const hasMore = ref(true);
        const isLoading = ref(false);
        const currentPage = ref(1);

        // ===== 计算属性 =====
        // 移除containerStyle计算属性，直接在CSS中使用v-bind

        // ===== 方法函数 =====
        // 处理头部高度变化
        const handleHeaderHeightChange = (heightInfo) => {
            headerHeight.value = heightInfo.totalHeaderHeight;
        };

        // 处理底部高度变化
        const handleBottomHeightChange = (heightInfo) => {
            bottomHeight.value = heightInfo.totalBottomHeight;
        };

        // 处理搜索输入
        const handleSearchInput = () => {
            // TODO: 实现搜索逻辑
            console.log('搜索关键词:', searchKeyword.value);
        };

        // 处理搜索按钮点击
        const handleSearchButtonClick = () => {
            // TODO: 执行搜索
            loadWorksList();
        };

        // 处理筛选标签点击
        const handleFilterTagClick = (filter) => {
            currentFilter.value = filter;
            // TODO: 根据筛选条件重新加载数据
            loadWorksList();
        };

        // 处理排序按钮点击
        const handleSortButtonClick = () => {
            uni.showActionSheet({
                itemList: ['按票数排序', '按时间排序', '按浏览排序'],
                success: (res) => {
                    // TODO: 根据选择进行排序
                    console.log('选择排序方式:', res.tapIndex);
                }
            });
        };

        // 处理作品项点击
        const handleWorkItemClick = (work) => {
            uni.navigateTo({
                url: `/pages-vote/EntryDetail?id=${work.id}`
            });
        };

        // 处理投票按钮点击
        const handleVoteButtonClick = (work) => {
            if (work.hasVoted) {
                uni.showToast({
                    title: '您已经投票给此作品',
                    icon: 'none'
                });
                return;
            }

            uni.showModal({
                title: '确认投票',
                content: `确定要投票给"${work.title}"吗？`,
                success: (res) => {
                    if (res.confirm) {
                        // TODO: 调用投票接口
                        work.hasVoted = true;
                        work.votes += 1;
                        uni.showToast({
                            title: '投票成功',
                            icon: 'success'
                        });
                    }
                }
            });
        };

        // 处理加载更多按钮点击
        const handleLoadMoreButtonClick = () => {
            if (isLoading.value) return;
            loadMoreWorks();
        };

        // 处理底部导航点击
        const handleTabClick = (item) => {
            console.log('切换到:', item.path);
        };

        // ===== 生命周期钩子 =====
        onMounted(() => {
            // 可以在这里加载实际数据
            loadWorksList();
        });

        // 加载作品列表数据
        const loadWorksList = async () => {
            try {
                isLoading.value = true;
                // TODO: 调用实际接口获取数据
                // const res = await getWorksList({
                //     keyword: searchKeyword.value,
                //     filter: currentFilter.value,
                //     page: 1,
                //     pageSize: 10
                // });
                // worksList.value = res.list;
                // totalCount.value = res.total;

                // 模拟加载延迟
                setTimeout(() => {
                    isLoading.value = false;
                }, 1000);
            } catch (error) {
                console.error('加载作品列表失败:', error);
                uni.showToast({
                    title: '加载数据失败',
                    icon: 'none'
                });
                isLoading.value = false;
            }
        };

        // 加载更多作品数据
        const loadMoreWorks = async () => {
            if (isLoading.value) return;

            isLoading.value = true;

            try {
                // TODO: 调用实际接口获取更多数据
                // const res = await getWorksList({
                //     keyword: searchKeyword.value,
                //     filter: currentFilter.value,
                //     page: currentPage.value + 1,
                //     pageSize: 10
                // });

                // 模拟加载更多数据
                setTimeout(() => {
                    const newWorks = [
                        {
                            id: worksList.value.length + 1,
                            title: '新作品D',
                            author: '赵六',
                            description: '这是一个新的参赛作品，展示了独特的创意和想法',
                            image: '/static/images/work4.jpg',
                            votes: 98,
                            views: 145,
                            comments: 12,
                            rank: 4,
                            hasVoted: false,
                            createTime: '2024-03-12',
                            category: '创意设计'
                        }
                    ];

                    worksList.value.push(...newWorks);
                    currentPage.value += 1;

                    // 模拟没有更多数据
                    if (currentPage.value >= 3) {
                        hasMore.value = false;
                    }

                    isLoading.value = false;
                }, 1000);

            } catch (error) {
                console.error('加载更多作品失败:', error);
                uni.showToast({
                    title: '加载失败',
                    icon: 'none'
                });
                isLoading.value = false;
            }
        };

        // ===== 返回数据和方法 =====
        return {
            // 响应式对象
            headerHeight,
            bottomHeight,
            searchKeyword,
            currentFilter,
            worksList,
            totalCount,
            hasMore,
            isLoading,
            currentPage,

            // 计算属性
            // containerStyle, // 移除

            // 方法函数
            handleHeaderHeightChange,
            handleBottomHeightChange,
            handleSearchInput,
            handleSearchButtonClick,
            handleFilterTagClick,
            handleSortButtonClick,
            handleWorkItemClick,
            handleVoteButtonClick,
            handleLoadMoreButtonClick,
            handleTabClick,
            loadWorksList,
            loadMoreWorks
        };
    },
    // 组件之间交互事件
    methods: {

    },
    // 生命周期 - 创建完成（访问DOM元素）
    beforeCreate() {

    },
    // 生命周期 - 创建完成（访问当前this实例）
    created() {

    },
    // 生命周期 - 挂载完成（访问当前this实例）
    mounted() {

    },
    // 生命周期 - 更新之前（访问当前this实例）
    beforeUpdate() {

    },
    // 生命周期 - 更新之前（访问当前this实例）
    updated() {

    },
    // 生命周期 - 销毁之前（访问当前this实例）
    unmounted() {

    },
    // 生命周期 - 组件激活（访问当前this实例）
    activated() {

    },
    // 生命周期 - 组件停用（访问当前this实例）
    deactivated() {

    },
    // 生命周期 - 子孙组件错误时
    errorCaptured() {

    }
});
</script>
<style lang='less' scoped>
/* scoped 使用得定义的样式只在本页面内生效  */
.container {
    width: 100%;
    min-height: 100vh;
    background-color: #f5f5f5;
    padding-top: v-bind('headerHeight + "px"');
    padding-bottom: v-bind('bottomHeight + "px"');

    // 搜索栏
    .search-section {
        margin: 20rpx;
        padding: 20rpx;
        background-color: #ffffff;
        border-radius: 16rpx;
        box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

        .search-box {
            display: flex;
            align-items: center;
            background-color: #f8f8f8;
            border-radius: 30rpx;
            padding: 20rpx 30rpx;

            .search-input {
                flex: 1;
                margin-left: 20rpx;
                font-size: 28rpx;
                color: #333;
            }

            .search-btn {
                margin-left: 20rpx;
                padding: 10rpx 30rpx;
                background-color: #007AFF;
                color: #ffffff;
                border-radius: 25rpx;
                font-size: 26rpx;
            }
        }
    }

    // 筛选标签
    .filter-section {
        margin: 0 20rpx 20rpx;
        padding: 20rpx;
        background-color: #ffffff;
        border-radius: 16rpx;
        box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

        .filter-scroll {
            white-space: nowrap;
        }

        .filter-tags {
            display: flex;
            gap: 20rpx;

            .filter-tag {
                display: inline-flex;
                align-items: center;
                justify-content: center;
                padding: 15rpx 30rpx;
                background-color: #f8f8f8;
                border-radius: 25rpx;
                font-size: 26rpx;
                color: #666;
                transition: all 0.3s;

                &.active {
                    background-color: #007AFF;
                    color: #ffffff;
                }
            }
        }
    }

    // 作品列表
    .works-section {
        margin: 0 20rpx 20rpx;

        .works-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20rpx;

            .works-count {
                font-size: 28rpx;
                color: #666;
            }

            .sort-btn {
                display: flex;
                align-items: center;
                padding: 10rpx 20rpx;
                background-color: #f8f8f8;
                border-radius: 20rpx;
                font-size: 24rpx;
                color: #666;

                view {
                    margin-left: 8rpx;
                }
            }
        }

        .works-list {
            .work-item {
                display: flex;
                align-items: flex-start;
                padding: 30rpx;
                margin-bottom: 20rpx;
                background-color: #ffffff;
                border-radius: 16rpx;
                box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

                .work-image-container {
                    position: relative;
                    width: 160rpx;
                    height: 160rpx;
                    flex-shrink: 0;
                    margin-right: 20rpx;

                    .work-image {
                        width: 100%;
                        height: 100%;
                        border-radius: 12rpx;
                    }

                    .work-rank {
                        position: absolute;
                        top: 10rpx;
                        right: 10rpx;
                        background-color: #ff4757;
                        color: #ffffff;
                        padding: 4rpx 12rpx;
                        border-radius: 20rpx;
                        font-size: 20rpx;
                    }
                }

                .work-info {
                    flex: 1;
                    margin-right: 20rpx;

                    .work-title {
                        font-size: 32rpx;
                        font-weight: bold;
                        color: #333;
                        margin-bottom: 10rpx;
                    }

                    .work-author {
                        font-size: 26rpx;
                        color: #666;
                        margin-bottom: 10rpx;
                    }

                    .work-desc {
                        font-size: 28rpx;
                        color: #666;
                        margin-bottom: 20rpx;
                        display: -webkit-box;
                        -webkit-box-orient: vertical;
                        -webkit-line-clamp: 2;
                        overflow: hidden;
                        line-height: 1.5;
                    }

                    .work-stats {
                        display: flex;
                        gap: 30rpx;
                        margin-bottom: 15rpx;

                        .stat-item {
                            display: flex;
                            align-items: center;

                            .stat-text {
                                font-size: 24rpx;
                                color: #666;
                                margin-left: 8rpx;
                            }
                        }
                    }

                    .work-meta {
                        display: flex;
                        gap: 30rpx;

                        .meta-item {
                            display: flex;
                            align-items: center;

                            .meta-text {
                                font-size: 24rpx;
                                color: #999;
                                margin-left: 6rpx;
                            }
                        }
                    }
                }

                .work-actions {
                    .vote-btn {
                        min-width: 140rpx;
                        height: 60rpx;
                        background-color: #007AFF;
                        color: #ffffff;
                        border: none;
                        border-radius: 30rpx;
                        font-size: 26rpx;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        padding: 0 20rpx;

                        &.voted {
                            background-color: #999;
                        }
                    }
                }
            }
        }

        .load-more {
            margin-top: 30rpx;
            text-align: center;

            .load-more-btn {
                display: inline-flex;
                align-items: center;
                justify-content: center;
                padding: 20rpx 40rpx;
                background-color: #f8f8f8;
                border-radius: 30rpx;
                font-size: 28rpx;
                color: #666;
            }
        }

        .empty-state {
            text-align: center;
            padding: 100rpx 0;

            .empty-text {
                font-size: 32rpx;
                color: #999;
                margin: 20rpx 0 10rpx;
            }

            .empty-desc {
                font-size: 26rpx;
                color: #ccc;
            }
        }
    }
}
</style>